<?php

namespace App\Http\Controllers\Comment;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\CommentContent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CommentController extends Controller
{
    use ResponseData;
    public function list(Comment $comment,Request $request){
        $openid = $request->openid;
        $status = $request->input('status',0);
        $size = $request->input('size',10);
        $data = $comment
            ->with('comments')
            ->when($request->myself,function($query)use($openid){
            return $query->where('openid',$openid);
        })
            ->when($status,function($query)use($status){
                return $query->where('status',$status);
            })
            ->where('is_show',1)
            ->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }

    public function update(CommentContent $comment,Request $request){
        $comments = Comment::query()->find($request->commons_id);
        $comments->status = $request->status;
        $comments->save();
        CommentContent::where('commons_id',$request->commons_id)->delete();
        $comments->comments()->createMany($request->comments);
        return $this->success('更新成功');
    }
    public function add(Comment $comment,Request $request){
            $map = [
                'avatar'=>$request->avatar,
                'common_user'=>$request->common_user,
                'openid'=>$request->openid,
                'car_id'=>$request->car_id??0,
            ];
            try{
                DB::beginTransaction();
                $res = $comment->create($map);
                if($request->filled('comments')){
                    $res->comments()->createMany($request->comments);
                }
                DB::commit();
                return $this->success('添加成功');
            }catch (\Exception $e){
                info($e->getMessage());
                DB::rollBack();
            }

    }
    //评论详情
    public function show(CommentContent $comment,Request $request){
        $data = $comment->find($request->id);
        return $this->success($data);
    }
}
